import os
import E_command
import subprocess
import sys

def inf():
    model_name = "Elysium_command_run"
    model_function = "Python文件运行器，可以自动运行指定的python文件，此过程中自动安装运行库并且自动在新窗口运行代码！"
    return model_name, model_function

def install_and_import(package):

    try:
        __import__(package)
        return True
    except ImportError:
        E_command.command_code(f"正在安装 {package} 库")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])
            E_command.command_code(f"{package} 库安装成功")
            return True
        except subprocess.CalledProcessError as e:
            E_command.command_warn(f"【{package} 库安装失败】错误信息: {e}")
            return False


def detect_required_packages(script_path):

    E_command.command("库文件检测")
    required_packages = set()

    with open(script_path, "r") as file:
        for line in file:
            # Basic detection of import statements
            if line.startswith("import ") or line.startswith("from "):
                parts = line.split()
                # Handle 'import package' or 'from package import ...'
                if len(parts) > 1:
                    package = parts[1].split(".")[0]
                    required_packages.add(package)

    E_command.command(f"检测到的库文件: {', '.join(required_packages)}")
    return required_packages


def main(script_path):

    # Step 1: Detect required packages
    packages = detect_required_packages(script_path)

    # Step 2: Install missing packages
    all_installed = True
    for package in packages:
        if not install_and_import(package):
            all_installed = False

    # Step 3: Run the script if all packages were installed successfully
    if all_installed:
        E_command.command("代码运行中")
        try:
            # Command to open a new terminal window and execute the script
            if sys.platform.startswith("win"):
                subprocess.Popen(["start", "cmd", "/k", f"{sys.executable} {script_path}"], shell=True)
            elif sys.platform.startswith("darwin"):
                subprocess.Popen(["open", "-a", "Terminal", f"{sys.executable} {script_path}"])
            else:  # Assuming Linux or other Unix-based systems
                subprocess.Popen(["gnome-terminal", "--", sys.executable, script_path])
            E_command.command("运行结束")
        except Exception as e:
            E_command.command_warn(f"运行失败，错误信息: {e}")
    else:
        E_command.command_warn("部分库安装失败，无法运行代码")

if __name__ == "__main__":
    # 需要指定要运行的 Python 文件路径
    script_path = "py.py"
    main(script_path)
